﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlanetTrack : MonoBehaviour {

    const float Grav = 6.67408E-11f;
    private GameObject MoveablePlanet;
    private GameObject StationaryStar;
    private PlanetClass MoveablePlanetClass;
    private PlanetClass StationaryStarClass;
    private Rigidbody MoveablePlanetRigidbody;
    private Rigidbody StationaryStarRigidbody;

    private float Distance;
    private float GravPower;
    private float PowerToCenter;
    private Vector3 Force;

    void Start()
    {
        MoveablePlanet = this.gameObject;
        MoveablePlanetClass = MoveablePlanet.GetComponent<PlanetClass>();
        MoveablePlanetRigidbody = MoveablePlanet.GetComponent<Rigidbody>();
    }

    public void Track(GameObject other)
    {
        StationaryStar = other;
        StationaryStarClass = StationaryStar.GetComponent<PlanetClass>();
        StationaryStarRigidbody = StationaryStar.GetComponent<Rigidbody>();
        Distance = Vector3.Distance(MoveablePlanet.transform.position, StationaryStar.transform.position);
        if (Distance >= 10f * Mathf.Min(MoveablePlanetClass.Radious, StationaryStarClass.Radious))
        {
            
            //计算万有引力
            GravPower = (Grav * MoveablePlanetClass.Mass * StationaryStarClass.Mass) / (Mathf.Pow(Distance, 2));
            //计算向心力
            PowerToCenter = (MoveablePlanetClass.Mass * Mathf.Pow(Vector3.Magnitude(MoveablePlanetRigidbody.velocity),2));
            //计算加速度
            Force = (GravPower - PowerToCenter) * Vector3.Normalize(MoveablePlanet.transform.position - StationaryStar.transform.position);
            //改变行星速度
            MoveablePlanetRigidbody.velocity += Force / MoveablePlanetClass.Mass;
            Debug.Log("speed"+MoveablePlanetRigidbody.velocity);
            
        }
        else
        {
            //
        }

    }
}
